package com.fare.taluo.io.excel;

import java.io.IOException;
import java.io.OutputStream;

import jxl.Workbook;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.log4j.Logger;
/**
 * Excel导出父类<br/>采用jxl
 * 导出的样式目前有一个经典样式ExcelExportClassicStyle
 * 应用可继承此类构建自己的样式后，再构建表格
 * 或者继承经典样式类，若有不满足的特殊样式，可以实现类中自己实例化，再构建表格
 * @author xiangsf 2012-6-6
 *
 */
public abstract class ExportExcel implements IExportExcel {

		protected Logger logger = Logger.getLogger(getClass());
		
		public ExportExcel(){
			try {
				initExcelFormat();
			} catch (WriteException e) {
			}
		}
		/**
		 * 初始化样式
		 * @throws WriteException
		 */
		protected abstract void initExcelFormat() throws WriteException;
		/**
		 * 构建Sheet
		 * @param workBook
		 * @throws ExcelExportException
		 */
		protected abstract void fillSheet(WritableWorkbook workBook) throws Exception;
		/**
		 * 清除资源
		 */
		protected abstract void clearResource();
		/**
		 * 创建Excel表格输出
		 * 业务对外接口方法,供外界调用
		 * @param os
		 * @throws ExcelExportException
		 */
		@Override
		public OutputStream writeExcel(OutputStream os) throws ExcelExportException{
			WritableWorkbook workBook = null;

			try {
				workBook = Workbook.createWorkbook(os);
				fillSheet(workBook);
				workBook.write();
			}catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
				throw new ExcelExportException("导出Excel异常:"+e.getMessage(),e);
			}finally{
				this.clearResource();
				this.close(workBook);
			}
			return os;
		}
		/**
		 * 关闭资源
		 * 其中OutputStream资源由应用自己去销毁
		 * @param workBook
		 * @param os
		 */
		private void close(WritableWorkbook workBook){
			if (workBook != null) {
				try {
					workBook.close();
				} catch (WriteException e) {
					logger.error(e);
				} catch (IOException e) {
					logger.error(e);
				}
				workBook=null;
			}
		}

}
